package com.chao.demo.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author chao
 */
public class DateUtil {

    private static final SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

    public static Date parse(String dateString) {
        Date date = null;
        try {
            // 使用SimpleDateFormat不是线性安全的，它以共享变量出现时，并发多线程场景下即会报错
            //一； date = simpleDateFormat.parse(dateString);
            date = dateFormatThreadLocal.get().parse(dateString); // 二、加上ThreadLocal 不会出现
            // 三、该方法加上synchronized （可能效率地）
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    public static void main(String[] args) {
        // 开始时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("开始时间：" + LocalDateTime.now().format(formatter));

        // 10个线程
        ExecutorService executorService = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 1000; i++) {
            String s = String.valueOf(i);
            executorService.execute(() -> {
                System.out.println(DateUtil.parse("2022-10-241 16:34:3" + s));
            });
        }
        executorService.shutdown();
    }

}

